package com.tedu.egspringbootmvc.common.intercepor;

import com.tedu.egspringbootmvc.common.result.JsonResult;
import com.tedu.egspringbootmvc.common.result.StatusCode;
import com.tedu.egspringbootmvc.pojo.vo.UserVO;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckLogininterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session=request.getSession();
        // 提供session获取用户信息
        UserVO userVO=(UserVO)session.getAttribute("user");
        if(userVO==null){
            // 未登录，重定向到登录页面
            // 返回json 并设置未中文编码
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(new JsonResult(StatusCode.NOT_LOGIN).toString());
            response.sendRedirect("/index.html");
            return false;
        }else {
            return true;
        }
    }
}
